#include "lessoncreation.h"
#include "ui_lessoncreation.h"
#include "listitem.h"
#include <QIcon>
#include <QFileDialog>
#include <QDesktopServices>
#include <QFile>
#include <QMessageBox>
#include <QTextStream>
#include <iostream>

LessonCreation::LessonCreation(QWidget *parent) :
    QWidget(parent),
    l_ui(new Ui::LessonCreation)
{
    l_ui->setupUi(this);
    alreadyAdded = QStringList();
}

/*
this function creates a dialog where the user selects the videos that they would like in the lesson
the selected videos are then added to a qlist, a check is run to see if the list already has a video in it if it does the video is not added again
*/
void LessonCreation::addFiles()
{
    QStringList files = QFileDialog::getOpenFileNames(this, tr("Select Image Files"), //seting up the dialog
        QDesktopServices::storageLocation(QDesktopServices::HomeLocation),QString("Images: *.jpg (*.jpg)")); //only show the jpg in the dialog

    if (files.isEmpty())
        return;

    foreach (QString string, files) {
        QFileInfo fi(string); //get the file info
        if (alreadyAdded.contains(string, Qt::CaseInsensitive)) //check for duplicates
            continue;
        l_ui->loadedListWid->addItem(
                new ListItem(string, l_ui->loadedListWid)); //adding item to list
        alreadyAdded += string; //appending the string list
    }
    //l_ui->loadedListWid->addItems(files);
}

/*
this function is used to load already made lessons so that they can be edited
*/
void LessonCreation::loadLesson()
{
    QString filename = QFileDialog::getOpenFileName(this, tr("Select Lesson"),
                    QString("lessons/"), QString("Lessons: *.ls (*.ls)")); //setting up the dialog so that the user can select the lessons with extension .ls
    if (filename == 0 || filename == "")
        return;
    QFile file(filename);//creating the file of the filename
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return; //checking to see if the file can be opened

    l_ui->lessonName->setText(QFileInfo(filename).baseName()); //setting the lesson name from the file
    shiftAllLeft(); //adding all the files to the left hand list

    while(!file.atEnd()) //while the file has not ended
    {
        QString n(file.readLine().trimmed()); //reading the line from the file
        if (alreadyAdded.contains(n)) //check to see if the file contains the string
        {
            QList<QListWidgetItem*> list(l_ui->loadedListWid->findItems(
                    QString(QFileInfo(n).baseName()), Qt::MatchFixedString)); //creating a QListeWidgetItem for each filename
            foreach (QListWidgetItem* wi, list)
            {
                l_ui->loadedListWid->setCurrentItem(wi); //loading the list item
                l_ui->loadedListWid->takeItem(l_ui->loadedListWid->currentRow()); //getting the next list item

                l_ui->selectedListWid->addItem(wi); //adding an item to the list
                //std::cout << wi->text().toStdString() << std::endl;
            }
            continue;
        }
        l_ui->selectedListWid->addItem(new ListItem(n, l_ui->selectedListWid)); //adding another item to the list
        alreadyAdded += n; //appending the list of already added items
    }
}

/*
this function is used to shift a single video from the left hand ;list view to the right hand one
*/
void LessonCreation::shiftRight()
{
    l_ui->selectedListWid->addItem(l_ui->loadedListWid->takeItem(l_ui->loadedListWid->currentRow())); //shifting the list itme from the left hand side to the right hand side
}
/*
this function is used to shifts all the videso to the selected videos view
*/
void LessonCreation::shiftAllRight()
{
    while (l_ui->loadedListWid->count() > 0) //while loop runs aslong as there are videos to be moved
        l_ui->selectedListWid->addItem(l_ui->loadedListWid->takeItem(0)); //shifting the videos from the left list to the right list
}
/*
this function shifts a video from the selected videos list to the available videos list
*/
void LessonCreation::shiftLeft()
{
    l_ui->loadedListWid->addItem(l_ui->selectedListWid->takeItem(l_ui->selectedListWid->currentRow())); //shifting the video from the right to the left list
}
/*
this function shifts all the videos from the selcted videos list to the available videos list
*/
void LessonCreation::shiftAllLeft()
{
    while (l_ui->selectedListWid->count() > 0) //same as shift All right
        l_ui->loadedListWid->addItem(l_ui->selectedListWid->takeItem(0));
}
/*
this function save the selected videos address to a file with the name of the lesson
*/
void LessonCreation::saveLesson()
{
    QString lessonName = QString("lessons/").append(l_ui->lessonName->text())
                         .append(".ls"); //creating the file name
    QFile file(lessonName);

    int ret = QMessageBox::Save;
    if (file.exists(lessonName)) //check to see if the file exists
    {
        QMessageBox msgBox;//creating a message box
        msgBox.setText("The lesson you selected already exists.");//setting the message box text
        msgBox.setInformativeText("Do you want to overwrite it?");//asking the user about an over write
        msgBox.setStandardButtons(QMessageBox::Save | QMessageBox::Cancel);//setting the buttons
        msgBox.setDefaultButton(QMessageBox::Save);//setting the default focus on the save button
        ret = msgBox.exec();//display the message box
    }
/*
this switch syament is ued for when the different buttons are clicked
*/
    switch (ret) {
    case QMessageBox::Save://if save is clicked
        if (file.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text))
        {
            QTextStream out(&file);//the file is opened withe the lesson name
            for (int i = 0; i < l_ui->selectedListWid->count(); i++)//the list is iterated through
                out << ((ListItem*)l_ui->selectedListWid->item(i))->getFileName().append("\n");//the video addresses are written to the file
            out.flush();//flushing the file witer
            file.close();//closing the file writer
            emit addedNewLesson();//emmiting the addnewlesson signal
        }
       break;
    case QMessageBox::Discard://id the discard button is clicked
       break;
    case QMessageBox::Cancel://if the cancel button is clicked
       return;
    default:
       // should never be reached
       break;
    }
}

LessonCreation::~LessonCreation()
{
    delete l_ui;
}

/*
this function is created by QT
*/
void LessonCreation::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        l_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}
